<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               title="物联信息"
               :modal="false"
               class="user-dialog add-or-updata"
               width="70%"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="dataForm"
               v-loading="dataListLoading"
               :element-loading-text="$t('loading')"
               ref="dataForm"
               label-position="left"
               @keyup.enter.native="dataFormSubmitHandle()"
               label-width="80px">
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="所属网关"
                          prop="gatewayId"
                          :rules="required()">
              <el-select v-model="dataForm.gatewayId"
                         clearable
                         class="width-100"
                         @change="changegateway"
                         placeholder="请选择所属网关">
                <el-option v-for="item in gatewayList"
                           :key="item.id"
                           :label="item.deviceId + '(' + item.name + ')'"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop='ip'
                          label="网关IP">
              <el-input v-model.trim='dataForm.ip'
                        class="width-100"
                        disabled
                        placeholder=''></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item prop='port'
                          label="网关端口">
              <el-input v-model.trim='dataForm.port'
                        class="width-100"
                        disabled
                        placeholder=''></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="规约协议"
                          prop="agreement"
                          :rules="required()">
              <el-select v-model="dataForm.agreement"
                         clearable
                         @change="changeagreement"
                         class="width-100"
                         placeholder="请选择">
                <el-option v-for="item in agreementList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop='deviceAddr'
                          label="设备地址"
                          :rules="stringRule(true, 1, 50)">
              <el-input v-model.trim='dataForm.deviceAddr'
                        class="width-100"
                        placeholder=''></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop='gatherPort'
                          label="采集端口"
                          :rules="stringRule(true, 1, 50)">
              <el-input v-model.trim='dataForm.gatherPort'
                        class="width-100"
                        placeholder=''></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="dataForm.agreement === 4">
        <div style="text-align: right;">
          <el-button type="primary"
                     plain
                     @click="addRow()">添加一行</el-button>
        </div>
        <table-template :loading='dataListLoading'
                        :fieldManagement='false'
                        :index='true'
                        style="width: 100%;height: 100%;"
                        :dataList='dataList'>
          <el-table-column prop="controlCode"
                           label="控制码"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.controlCode"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataFieldLength"
                           label="数据域长度"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataFieldLength"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="requestDataDomain"
                           label="请求数据域"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.requestDataDomain"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataStartBit"
                           label="接收数据起始位"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataStartBit"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataEndBit"
                           label="接受数据结束位"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataEndBit"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataIdentification"
                           label="数据标识"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataIdentification"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="magnification"
                           label="倍率"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.magnification"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataSorting"
                           label="数据排序"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.dataSorting"
                               controls-position="right"
                               style="width: 100%"
                               :min="0"
                               :max="999999999"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="dataUnit"
                           label="数据单位"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataUnit"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('handle')"
                           fixed='right'
                           header-align='center'
                           align='center'
                           width='120'>
            <template slot-scope='scope'>
              <el-button @click="test(scope.row)"
                         type="text"
                         size="mini"
                         :loading="istest"
                         class="band">测试</el-button>
              <el-button type='text'
                         size='small'
                         class='danger'
                         @click='deleteRow(scope.row)'>{{ $t('delete') }}</el-button>
            </template>
          </el-table-column>
        </table-template>
      </div>
      <div v-if="dataForm.agreement === 5">
        <div style="text-align: right;">
          <el-button type="primary"
                     plain
                     @click="addRow1()">添加一行</el-button>
        </div>
        <table-template :loading='dataListLoading'
                        :fieldManagement='false'
                        :index='true'
                        style="width: 100%;height: 100%;"
                        :dataList='dataList'>
          <el-table-column prop="type"
                           label="类型"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.type"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="controlCode"
                           label="控制码"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model.trim="scope.row.controlCode"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataFieldLength"
                           label="数据域长度"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataFieldLength"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="serialNumber"
                           label="序列号"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.serialNumber"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="requestDataDomain"
                           label="请求数据域"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.requestDataDomain"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="opcode"
                           label="操作码"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.opcode"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataStartBit"
                           label="接收数据起始位"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataStartBit"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataEndBit"
                           label="接受数据结束位"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataEndBit"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataIdentification"
                           label="数据标识"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataIdentification"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="magnification"
                           label="倍率"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.magnification"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dataSorting"
                           label="数据排序"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.dataSorting"
                               controls-position="right"
                               style="width: 100%"
                               :min="0"
                               :max="999999999"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="dataUnit"
                           label="数据单位"
                           min-width="150"
                           align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dataUnit"
                        style="width: 100%"
                        placeholder=''></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="diDataCode"
                             label="DI数据代码"
                             min-width="150"
                             align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.diDataCode"
                          style="width: 100%"
                          placeholder=''></el-input>
              </template>
            </el-table-column>
          <el-table-column :label="$t('handle')"
                           fixed='right'
                           header-align='center'
                           align='center'
                           width='120'>
            <template slot-scope='scope'>
              <el-button @click="test(scope.row)"
                         type="text"
                         size="mini"
                         :loading="istest"
                         class="band">测试</el-button>
              <el-button type='text'
                         size='small'
                         class='danger'
                         @click='deleteRow(scope.row)'>{{ $t('delete') }}</el-button>
            </template>
          </el-table-column>
        </table-template>
      </div>
      <template slot="footer">
        <el-button @click="closeDialog()">{{ $t("cancel") }}</el-button>
        <el-button type="primary"
                   :loading="dataListLoading"
                   @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
      </template>
    </el-dialog>
    <el-dialog title=""
               :visible.sync="dialogVisible"
               width="30%"
               :before-close="handleClose">
      <el-form :model="resultObj"
               v-loading="dataListLoading"
               :element-loading-text="$t('loading')"
               ref="resultObj"
               label-position="left"
               label-width="80px">
        <el-form-item prop="result"
                      label="读数："
                      :rules="required()">
          <el-input v-model="resultObj.result"
                    disabled
                    placeholder=""></el-input>
        </el-form-item>
        <el-form-item prop="dataUnit"
                      label="单位："
                      :rules="required()">
          <el-input v-model="resultObj.dataUnit"
                    disabled
                    placeholder=""></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose()">取 消</el-button>
        <el-button type="primary"
                   @click="dataFormSubmitHandle1()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import tableTemplate from '@/components/table-template'
export default {
  mixins: [mixinViewModule, minFormValidate],
  data () {
    return {
      mixinViewModuleOptions: {
        deleteImgURL: '/system/oss/delete',
        getDataListURL: '', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        addURL: 'tb/device/insertDevice', // 添加或修改接口，API地址
        updateURL: 'tb/device/updateDevice', // 添加或修改接口，API地址
        getDataInfoURL: '', // 数据详情，API地址
        deleteURL: '', // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      visible: false,
      dataForm: {
        gatewayId: '',
        agreement: 4,
        deviceAddr: '',
        gatherPort: ''
      },
      agreementList: [
        { id: 4, name: 'DLT645_2007' },
        { id: 5, name: 'CJ188' },
        { id: 6, name: 'modbus_RTU' }],
      gatewayList: [],
      dataList: [],
      dialogVisible: false,
      resultObj: {},
      agreement: '',
      istest: false
    }
  },
  components: { tableTemplate },
  mounted () {
  },
  methods: {
    init (data) {
      this.dataForm.id = data.id
      this.dataForm.agreement = data.agreement
      this.agreement = data.agreement
      console.log(this.agreement)
      this.$nextTick(() => {
        if (this.dataForm.id) {
          this.$http.get('/tb/device/queryGatewayList').then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.gatewayList = res.data
          })
          this.getinformationByAgreement()
        }
      })
      this.visible = true
    },
    getinformationByAgreement () {
      let url = `tb/device/informationByAgreement?did=${this.dataForm.id}&agreement=${this.dataForm.agreement}`
      this.$http.get(url).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm.gatewayId = res.data.gatewayId
        this.dataForm.ip = res.data.ip
        this.dataForm.gatherPort = res.data.gatherPort
        this.dataForm.deviceAddr = res.data.deviceAddr
        this.dataList = res.data.parametersDltList || []
      })
    },
    test (data) {
      this.istest = true
      this.$http.get(`/tb/devicePolling/measurement?did=${this.dataForm.id}&gatewayId=${this.dataForm.gatewayId}&agreement=${this.dataForm.agreement}&deviceAddr=${this.dataForm.deviceAddr}&gatherPort=${this.dataForm.gatherPort}&controlCode=${data.controlCode}&dataFieldLength=${data.dataFieldLength}&requestDataDomain=${data.requestDataDomain}&dataStartBit=${data.dataStartBit}&dataEndBit=${data.dataEndBit}&dataIdentification=${data.dataIdentification}&magnification=${data.magnification}&dataSorting=${data.dataSorting}&dataUnit=${data.dataUnit}`).then(({ data: res }) => {
        if (res.code !== 0) {
          this.istest = false
          return this.$message.error(res.msg)
        }
        this.resultObj = res.data
        this.istest = false
        this.dialogVisible = true
      })
    },
    handleClose () {
      this.istest = false
      this.dialogVisible = false
      this.resultObj = {}
    },
    dataFormSubmitHandle1 () {
      this.handleClose()
    },
    changegateway (val) {
      this.dataForm.ip = ''
      this.gatewayList.map(item => {
        if (val === item.id) {
          this.dataForm.ip = item.ip
        }
      })
    },
    changeagreement (val) {
      console.log(this.agreement, val)
      if (this.agreement !== val) {
        this.dataList = []
      } else {
        this.getinformationByAgreement()
      }
    },
    // 删除行
    deleteRow (_row) {
      this.dataList.forEach((value, index, array) => {
        if (value.id === _row.id) {
          array.splice(index, 1)
        }
      })
    },
    // 新增行
    addRow () {
      this.dataList.push({
        // did: this.dataForm.id,
        controlCode: '',
        dataFieldLength: '',
        requestDataDomain: '',
        dataStartBit: '',
        dataEndBit: '',
        dataIdentification: '',
        magnification: '',
        dataSorting: 0,
        dataUnit: ''
      })
    },
    // 新增行
    addRow1 () {
      this.dataList.push({
        // did: this.dataForm.id,
        type: '',
        controlCode: '',
        dataFieldLength: '',
        serialNumber: '',
        requestDataDomain: '',
        opcode: '',
        dataStartBit: '',
        dataEndBit: '',
        dataIdentification: '',
        magnification: '',
        dataSorting: 0,
        dataUnit: '',
        diDataCode: ''
      })
    },
    closeDialog () {
      //   this.$refs.dataForm.resetFields()
      this.dataForm.agreement = 4
      this.dataForm.gatewayId = ''
      this.dataForm.deviceAddr = ''
      this.dataForm.ip = ''
      this.dataForm.gatherPort = ''
      this.dataList = []
      this.visible = false
      this.$emit('callBack')
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            let obj = {}
            obj.data = {}
            obj.data.did = this.dataForm.id
            obj.data.agreement = this.dataForm.agreement
            obj.data.gatewayId = this.dataForm.gatewayId
            obj.data.deviceAddr = this.dataForm.deviceAddr
            obj.data.gatherPort = this.dataForm.gatherPort
            obj.data.parametersDltList = []
            if (this.dataForm.agreement === 4) {
              for (let i = 0; i < this.dataList.length; i++) {
                // 数字0判断为否
                if (this.dataList[i].dataSorting === undefined || this.dataList[i].dataSorting === '' || this.dataList[i].dataSorting === null) {
                  this.dataList[i].dataSorting = 0
                }
                if (!this.dataList[i].controlCode || !this.dataList[i].dataFieldLength || !this.dataList[i].requestDataDomain || !this.dataList[i].dataStartBit || !this.dataList[i].dataEndBit || !this.dataList[i].dataIdentification || !this.dataList[i].magnification || !this.dataList[i].dataUnit) {
                  return this.$message.warning('协议数据信息不能为空,请填写后重试')
                }
              }
              obj.data.parametersDltList = this.dataList
              if (obj.data.parametersDltList.length === 0) {
                return this.$message.warning('协议数据信息不能为空,请填写后重试')
              }
            } else if (this.dataForm.agreement === 5) {
              if (!Array.isArray(this.dataList) || this.dataList.length === 0) {
                return this.$message.warning('协议数据信息不能为空,请填写后重试')
              }
              for (let i = 0; i < this.dataList.length; i++) {
                // 数字0判断为否
                if (this.dataList[i].dataSorting === undefined || this.dataList[i].dataSorting === '' || this.dataList[i].dataSorting === null) {
                  this.dataList[i].dataSorting = 0
                }
                if (!this.dataList[i].controlCode || !this.dataList[i].dataFieldLength || !this.dataList[i].requestDataDomain || !this.dataList[i].dataStartBit || !this.dataList[i].dataEndBit || !this.dataList[i].dataIdentification || !this.dataList[i].magnification || !this.dataList[i].dataUnit || !this.dataList[i].serialNumber || !this.dataList[i].type || !this.dataList[i].diDataCode) {
                  return this.$message.warning('协议数据信息不能为空,请填写后重试')
                }
              }
              obj.data.parametersDltList = this.dataList
            } else {
              return this.$message.warning('当前规约协议没有数据，请重新选择')
            }
            this.$http.put('tb/device/updateIOTInformation', obj).then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message.success('保存成功')
              this.closeDialog()
            })
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    )
  }
}
</script>

<style lang="scss" scoped></style>
